package com.lej.preview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.github.chrisbanes.photoview.PhotoView
import com.lej.preview.data.PicInfo
import com.qmuiteam.qmui.kotlin.onClick
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView

class PreFragment(private val info: PicInfo) : Fragment() {
    private var photoView: PhotoView? = null
    private var videoPlayer: StandardGSYVideoPlayer? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (info.type == 0) {
            photoView = PhotoView(activity).apply {
                layoutParams = ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            }
            return photoView
        } else {
            videoPlayer = StandardGSYVideoPlayer(activity).apply {
                layoutParams = ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            }
            return videoPlayer
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        photoView?.show()
        videoPlayer?.show()
    }

    private fun PhotoView.show() {
        Glide.with(this).load(info.url).into(this)
        setOnViewTapListener { _, _, _ -> activity?.onBackPressed() }
    }

    private fun StandardGSYVideoPlayer.show() {
        backButton?.visibility = View.GONE
        GSYVideoManager.instance().isNeedMute = false
        titleTextView.visibility = View.GONE
        isStartAfterPrepared = true
        setIsTouchWiget(false)
        isReleaseWhenLossAudio = false
        isNeedShowWifiTip = false
        isAutoFullWithSize = true
        playTag = toString()
        playPosition = hashCode()
        isLooping = true

        setUpLazy(info.url, true, null, null, "")

        onClick { activity?.onBackPressed() }
    }

    override fun onPause() {
        super.onPause()
        videoPlayer?.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        videoPlayer?.let {
            when (it.currentState) {
                GSYVideoView.CURRENT_STATE_PAUSE -> it.onVideoResume()
                GSYVideoView.CURRENT_STATE_NORMAL,
                GSYVideoView.CURRENT_STATE_PREPAREING -> it.startPlayLogic()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        videoPlayer?.release()
    }
}